package com.woniuxy.project115.kaer.tenant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.project115.kaer.commons.util.OSSUtil;
import com.woniuxy.project115.kaer.tenant.entity.ServiceInfo;
import com.woniuxy.project115.kaer.tenant.entity.ServiceInfoItem;
import com.woniuxy.project115.kaer.tenant.entity.TenantStore;
import com.woniuxy.project115.kaer.tenant.form.ServiceInfoItemForm;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceInfoItemMapper;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceInfoMapper;
import com.woniuxy.project115.kaer.tenant.mapper.TenantStoreMapper;
import com.woniuxy.project115.kaer.tenant.param.AddServiceInfoParam;
import com.woniuxy.project115.kaer.tenant.param.GetServiceInfoParam;
import com.woniuxy.project115.kaer.tenant.param.SelectServiceInfoParam;
import com.woniuxy.project115.kaer.tenant.param.ServiceInfoItemParam;
import com.woniuxy.project115.kaer.tenant.service.ServiceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project115.kaer.tenant.util.Data;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuH
 * @since 2025年02月19日
 */
@Service
public class ServiceInfoServiceImpl extends ServiceImpl<ServiceInfoMapper, ServiceInfo> implements ServiceInfoService {
    @Resource
    private ServiceInfoMapper serviceInfoMapper;

    @Resource
    private ServiceInfoItemMapper serviceInfoItemMapper;

    @Resource
    private TenantStoreMapper tenantStoreMapper;

    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        //判断上传的文件的真实类型
        //取出上传的文件的前4个字节，其中保存了文件的类型信息
        InputStream is = file.getInputStream();
        byte[] fileHeader=new byte[4];
        is.read(fileHeader);
        //调用API判断文件类型
        if(!(OSSUtil.isJpg(fileHeader)||OSSUtil.isPng(fileHeader))){
            throw new Exception("文件类型不支持");
        }
        //先获取文件的后缀名
        String suffix = StringUtils.getFilenameExtension(file.getOriginalFilename());
        String prefix= UUID.randomUUID().toString();
        //实现文件上传
        return OSSUtil.uploadFile(file.getInputStream(), prefix + "." + suffix, "kaer-service");
    }

    @Override
    public void addServiceInfo(AddServiceInfoParam param, Integer tenantInfoId) throws Exception {
        //新增服务商品信息
        ServiceInfo serviceInfo = BeanUtil.toBean(param, ServiceInfo.class);
        TenantStore store = tenantStoreMapper.selectOne(new QueryWrapper<TenantStore>().eq("tenant_info_id", tenantInfoId));
        if (store == null) {
            throw new Exception("店铺不存在");
        }
        serviceInfo.setStoreId(store.getStoreId())
                .setStoreName(store.getStoreName())
                .setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
                .setState(Data.SERVICE_INFO_OFFLINE);
        serviceInfoMapper.insert(serviceInfo);

        //新增具体服务项目（模板）
        for (ServiceInfoItemForm itemForm : param.getServiceInfoItems()) {
            ServiceInfoItem item = BeanUtil.toBean(itemForm, ServiceInfoItem.class);
            item.setServiceInfoId(serviceInfo.getServiceInfoId());
            serviceInfoItemMapper.insert(item);
        }
    }

    @Override
    public void online(Integer serviceInfoId) throws Exception {
        ServiceInfo serviceInfo = serviceInfoMapper.selectById(serviceInfoId);
        if (serviceInfo == null) {
            throw new Exception("服务商品信息不存在");
        }
        if (serviceInfo.getState() == Data.SERVICE_INFO_ONLINE) {
            throw new Exception("服务商品信息已上架");
        }
        serviceInfoMapper.updateById(serviceInfo.setState(Data.SERVICE_INFO_ONLINE));
    }

    @Override
    public void offline(Integer serviceInfoId) throws Exception {
        ServiceInfo serviceInfo = serviceInfoMapper.selectById(serviceInfoId);
        if (serviceInfo == null) {
            throw new Exception("服务商品信息不存在");
        }
        if (serviceInfo.getState() == Data.SERVICE_INFO_OFFLINE) {
            throw new Exception("服务商品信息已下架");
        }
        serviceInfoMapper.updateById(serviceInfo.setState(Data.SERVICE_INFO_OFFLINE));
    }

    @Override
    public Page<ServiceInfo> selectServiceInfo(SelectServiceInfoParam param, Integer storeId) throws Exception {
        Page<ServiceInfo> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<ServiceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        if (param.getNodeName() != null && !param.getNodeName().isEmpty()) {
            queryWrapper.like("node_name", param.getNodeName());
        }
        if (param.getTypeName() != null && !param.getTypeName().isEmpty()) {
            queryWrapper.eq("type_name", param.getTypeName());
        }
        if (param.getCreator() != null && !param.getCreator().isEmpty()) {
            queryWrapper.eq("creator", param.getCreator());
        }
        if (param.getState() != null && param.getState() != -1) {
            queryWrapper.eq("state", param.getState());
        }
        return serviceInfoMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Page<ServiceInfo> getServiceInfoByStoreId(GetServiceInfoParam param) throws Exception {
        Page<ServiceInfo> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<ServiceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", param.getStoreId())
                .eq("state", Data.SERVICE_INFO_ONLINE);
        if (param.getTypeName() != null && !param.getTypeName().isEmpty()) {
            queryWrapper.eq("type_name", param.getTypeName());
        }
        //按创建时间倒序排序
        queryWrapper.orderByDesc("create_time");
        return serviceInfoMapper.selectPage(page, queryWrapper);
    }
}
